package org.algorithm.Backtracking.leetcode39;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Solution {

    /**
     * 组合总和，candidates 中元素可以取多次
     */

    List<List<Integer>> res = new ArrayList<>();
    List<Integer> item = new ArrayList<>();

    public List<List<Integer>> combinationSum(int[] candidates, int target) {

        Arrays.sort(candidates);
        backtracking(candidates,target,0,0);
        return res;
    }

    private void backtracking(int [] candidates,int target,int sum,int index){
        if (sum==target){
            res.add(new ArrayList<>(item));
            return;
        }

        if (sum>target){
            return;
        }

        for (int i = index; i < candidates.length; i++) {
            sum+=candidates[i];
            item.add(candidates[i]);
            backtracking(candidates,target,sum,i);
            sum-=candidates[i];
            item.remove(item.size()-1);
        }

    }
}
